/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bulkmailer.email.sender;

import bulkmailer.beans.AccountSettings;
import bulkmailer.beans.Email;
import bulkmailer.beans.ServerSettings;
import bulkmailer.email.addr.manager.EMailAddressManager;
import bulkmailer.app.main.UI;
import bulkmailer.db.DBConnector;
import java.sql.Connection;
import java.util.TreeSet;
import org.apache.log4j.Logger;

/**
 *
 * @author ravi
 */
public class MailSender {

    public void sendMailToAll(AccountSettings accountSettings, ServerSettings serverSettings, Email email) {
        TreeSet<String> addrSet = this.getEmailAddress();
        setProgressBar(addrSet.size());
        SenderThread senderThread = new SenderThread(serverSettings, accountSettings, email, addrSet);
        Logger.getRootLogger().debug("starting thread on all");
        senderThread.start();
    }

    public void sendMailToDomains(AccountSettings accountSettings, ServerSettings serverSettings, Email email, TreeSet<String> domains) {
        TreeSet<String> addrSet = this.getEmailOnDomains(domains);
        setProgressBar(addrSet.size());
        SenderThread senderThread = new SenderThread(serverSettings, accountSettings, email, addrSet);
        senderThread.start();
    }

    public TreeSet<String> getEmailOnDomains(TreeSet<String> domains) {
        TreeSet<String> addrSet = null;
        try {
            Connection con = DBConnector.getConnection(DBConnector.SCHEMA_NAME);
            if (con == null) {
                Logger.getRootLogger().error("database connection faild");
                return null;
            } else {
                Logger.getRootLogger().debug("db connection ok");
            }
            EMailAddressManager mailPopper = new EMailAddressManager();
            Logger.getRootLogger().debug("getting addresses on domains");
            addrSet = mailPopper.getAddressesOfDomain(domains);
            Logger.getRootLogger().debug("address count : " + addrSet.size());

        } catch (Exception ex) {
            Logger.getRootLogger().error(ex.toString());
        }
        Logger.getRootLogger().debug("total address :" + addrSet.size());
        return addrSet;
    }

    public TreeSet<String> getEmailAddress() {
        TreeSet<String> addrSet = null;
        try {
            EMailAddressManager mailPopper = new EMailAddressManager();
            Logger.getRootLogger().debug("getting all addresses");
            addrSet = mailPopper.getAllAddress();
            Logger.getRootLogger().debug("address count : " + addrSet.size());
        } catch (Exception ex) {
            Logger.getRootLogger().error(ex.toString());
        }
        return addrSet;
    }

    private void setProgressBar(int maxSize) {
        UI.appsUi.sentMailCount = 0;
        UI.appsUi.markMailSentProgress();
        UI.appsUi.getMailSentProgress().setMaximum(maxSize);
    }
}
